<?php
/*
 *      c.idle.class.php
 *      
 *      Copyright 2009 Valery Tverdohleb <tvsdesign@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

class ControllerIdle implements Controller
{
	protected $state = array('mode' => 'idle');
	
	public static function Create()
	{
		if (Engine::get()->access->isSignedIn())
		{
			return self::_CreateAuthorized();
		}
		else
		{
			return self::_CreateUnauthorized();
		}
	}

	protected static function _CreateUnauthorized()
	{
		return ControllerFront::Create();
	}
	
	protected static function _CreateAuthorized()
	{
		return new self;
	}
	
	
	public function Render()
	{
		switch ($this->state['mode'])
		{
			case "talk":
			{
				$t = Engine::get()->player->talking();
				$dialog = Engine::get()->npc->dialog($t['talk']);
				$p = $dialog[$t['talk_s']]['text'];
				
				$answers = array();
				foreach ($dialog[$t['talk_s']]['next'] as $v)
				{
					$answers[] = array('text' => $dialog[$v]['text'], 'id' => $v);
				}
				$npcname = Engine::get()->npc->name($t['talk']);
				Engine::get()->smarty->assign('npcname',$npcname);
				Engine::get()->smarty->assign('npcsays',$p);
				Engine::get()->smarty->assign('answers',$answers);
				Engine::get()->smarty->display('base.talk.tpl');
				break;
			}
			case "map":
			{
				/*
				 * Передача структуры карты вблизи игрока в шаблон
				 */
				$cells = Engine::get()->map->cells(); //Получение ячеек
				Engine::get()->smarty->assign('cells',$cells); //Передача в шаблон
				//:TODO: Передача в шаблон массива для перебора ячеек (ИМХО костыль, надо поправить)
				Engine::get()->smarty->assign('iterator',array(-3,-2,-1,0,1,2,3));
				Engine::get()->smarty->display('base.pda.map.tpl'); //Генерация страницы
				break;
			}
			case "clist":
			{
				$contacts = Engine::get()->messaging->listContacts();
				Engine::get()->smarty->assign('contacts',$contacts);
				Engine::get()->smarty->display('base.pda.clist.tpl'); //Генерация страницы
				break;
			}
			case "msgcompose":
			{
				if (!is_numeric($_POST['i']))
				{
					throw new Application_Exception('Trying to send to anything but player.');
				}
				if (Engine::get()->messaging->isPlayerInPhonebook($_POST['i']) || Engine::get()->pmanager->isOnline($_POST['i']))
				{
					Engine::get()->smarty->assign('r',Engine::get()->pmanager->getPlayerDetails($_POST['i']));
					Engine::get()->smarty->display('base.pda.newpmsg.tpl'); //Генерация страницы
				}
				else
				{
					throw new Application_Exception('Trying to send msg to player nor online nor in clist.');
				}
				break;
			}
			case "msginbox":
			{
				Engine::get()->smarty->assign('messages',Engine::get()->messaging->listInbox());
				Engine::get()->smarty->display('base.pda.inbox.tpl'); //Генерация страницы
				break;
			}
			case "msgsent":
			{
				Engine::get()->smarty->assign('messages',Engine::get()->messaging->listSent());
				Engine::get()->smarty->display('base.pda.sent.tpl'); //Генерация страницы
				break;
			}
			case "msgread":
			{
				if (!is_numeric($_POST['i']))
				{
					throw new Application_Exception('Trying to send to anything but player.');
				}
				$msg = Engine::get()->messaging->getMessage($_POST['i']);
				Engine::get()->smarty->assign('message',$msg);
				Engine::get()->smarty->display('base.pda.readmsg.tpl');
				break;
			}
			case "bag":
			{
				switch ($_POST['d'])
				{
					case "pickup":
					{
						Engine::get()->inventory->takeItem($_POST['i']);
						$this->renderIdlePage();
						break;
					}
					case "throw":
					{
						Engine::get()->inventory->dropItem($_POST['i']);
						$this->renderBagPage();
						break;
					}
					case "equip":
					{
						$this->renderEquipmentPage();
						break;
					}
					case "wear":
					{
						if (Engine::get()->inventory->isItemInBag($_POST['i']))
						{
							Engine::get()->inventory->wearItem($_POST['i']);
						}
						$this->renderBagPage();
						break;
					}
					case "takeoff":
					{
						Engine::get()->inventory->takeOffItem($_POST['i']);
						$this->renderEquipmentPage();
						break;
					}
					default:
					{
						$this->renderBagPage();
					}
				}
				break;
			}
			case "touch":
			{
				switch ($this->state['who'])
				{
					case "player":
					{
						$touched = array('who' => 'player', 'id' => $this->state['id']);
						Engine::get()->smarty->assign('touched', $touched);
						break;
					}
					default:
					{
						throw new Application_Exception('Wrong input');
					}
				}
				$this->renderIdlePage();
				break;
			}
			case "indevelopment":
			case "idle":
			default:
			{
				$this->renderIdlePage();
			}
		}
	}
	
	protected function renderBagPage()
	{
		$items = Engine::get()->inventory->listItems();
		Engine::get()->smarty->assign('items',$items);
		Engine::get()->smarty->display('base.bag.tpl'); //Генерация страницы
	}
	
	protected function renderEquipmentPage()
	{
		$items = Engine::get()->inventory->getWearedItems();
		Engine::get()->smarty->assign('items',$items);
		Engine::get()->smarty->display('base.equipment.tpl'); //Генерация страницы
	}
	
	protected function renderIdlePage()
	{
		/*
		 * Пересчет разрешенных направлений движения
		 */
		if ((Engine::get()->player->coords('L') != 0) || (Engine::get()->player->talking()))
		{
			//Если игрок в здании или общается с NPC, то он не может ходить
			$moveEnabled = array('n' => false, 's' => false, 'e' => false, 'w' => false, 'u' => false, 'd' => false);
		}
		else
		{
			//Иначе определяем разрешенные направления по карте
			$moveEnabled = array(
							'n' => Engine::get()->map->isCellActive(0,1,0), //Север
							's' => Engine::get()->map->isCellActive(0,-1,0), //Юг
							'e' => Engine::get()->map->isCellActive(1,0,0), //Восток
							'w' => Engine::get()->map->isCellActive(-1,0,0), //Запад
							'u' => Engine::get()->map->isCellActive(0,0,1), //Выше
							'd' => Engine::get()->map->isCellActive(0,0,-1) //Ниже
						);
		}
		Engine::get()->smarty->assign('moveenabled',$moveEnabled); //Передаем в шаблон
		
		/*
		 * Вывод лежащих на земле предметов
		 */
		
		$itemsOnGround = Engine::get()->inventory->listItemsOnGround(Engine::get()->player->coords()); //Получаем список предметов
		Engine::get()->smarty->assign('itemsonground',$itemsOnGround); //Передаем в шаблон
		
		/*
		 * Вывод дверей в локации
		 */
		$doors = Engine::get()->map->doors(Engine::get()->player->coords()); //Получаем список дверей
		Engine::get()->smarty->assign('doors',$doors); //Передаем в шаблон
		
		/*
		 * Вывод игроков, находящихся на одних координатах с активным
		 */
		$players = Engine::get()->pmanager->listPlayersAtPos(Engine::get()->player->coords()); //Получаем список игроков
		unset($players[Engine::get()->player->getId()]); //Удаляем себя из списка
		Engine::get()->smarty->assign('players',$players); //Передаем в шаблон
		
		/*
		 * Вывод NPC
		 */
		$npcs = Engine::get()->npc->listNPCs(); //Получаем список NPC
		Engine::get()->smarty->assign('npcs',$npcs); //Передаем в шаблон
		
		/*
		 * Вывод мобов
		 */
		$mobs = Engine::get()->mobs->listMobsAtPos(Engine::get()->player->coords()); //Получаем список мобов
		Engine::get()->smarty->assign('mobs',$mobs); //Передаем в шаблон
		
		Engine::get()->smarty->display('base.index.idle.tpl'); //Генерация страницы
	}
	
	public function __construct()
	{
		switch ($_POST['m'])
		{
			case "pda":
			{
				switch ($_POST['d'])
				{
					case "map":
					{
						$this->state['mode'] = 'map';
						break;
					}
					case "sms":
					{
						$this->state['mode'] = 'clist';
						break;
					}
					case "msgcompose":
					{
						$this->state['mode'] = 'msgcompose';
						break;
					}
					case "inbox":
					{
						$this->state['mode'] = 'msginbox';
						break;
					}
					case "sent":
					{
						$this->state['mode'] = 'msgsent';
						break;
					}
					case "msgread":
					{
						$this->state['mode'] = 'msgread';
						break;
					}
					case "top":
					case "glossary":
					{
						$this->state['mode'] = 'indevelopment';
						break;
					}
					default:
					{
						throw new Application_Exception('Wrong input passed');
					}
				}
				break;
			}
			case "bag":
			{
				$this->state['mode'] = 'bag';
				break;
			}
			case "login":
			case "idle":
			default:
			{
				$this->state['mode'] = 'idle';
				if (Engine::get()->access->isSignedIn())
				{
					$result = Engine::get()->player->iterate();
					$this->state = $result;
				}
			}
		}
	}
}

?>
